{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 罗马数字转阿拉伯数字\n",
    "\n",
    "[![Author](https://img.shields.io/badge/Author-%40mjd507-important?style=social&logo=GitHub)](https://github.com/mjd507)\n",
    "[![WeChat Channel](https://img.shields.io/badge/Wechat-Daily%20Problem-important?style=social&logo=WeChat)](https://mp.weixin.qq.com/s/ev1M4tDUL_DozjKIG0TwsA)\n",
    "\n",
    "![Logo](img/Day79-1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "　　给定一串罗马数字，确定其十进制数值。输入的罗马数字将被限制在$1 \\leq x \\leq 3999$。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 用例说明\n",
    "\n",
    "```python\n",
    "In[1]:  IX\n",
    "Out[1]: 9\n",
    "\n",
    "In[2]:  VII\n",
    "Out[2]: 7\n",
    "\n",
    "In[3]:  MCMIV\n",
    "Out[3]: 1904\n",
    "```\n",
    "\n",
    "　　罗马数字基于以下字符：\n",
    "\n",
    "| 字母 | 数值 | 字母 | 数值 | 字母 | 数值 |\n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|\n",
    "|  I   |  1   |  XL  |  40  |  CD  | 400  |\n",
    "|  IV  |  4   |  L   |  50  |  D   | 500  |\n",
    "|  V   |  5   |  XC  |  90  |  CM  | 900  |\n",
    "|  IX  |  9   |  C   | 100  |  M   | 1000 |\n",
    "|  X   |  10  |\n",
    "\n",
    "　　数值是这些字符按降序排列。在一些情况下，减号用于避免重复字符，规则如下：\n",
    "1. `I`在`V`之前表示$-1$，因此`IV`是4、`IX`是9；\n",
    "2. `X`在`L`和`C`之前表示$-10$，因此`XL`是40、`XC`是90；\n",
    "3. 放在`D`或`M`前的`C`表示$-100$，因此`CD`是400、`CM`是900。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution():\n",
    "    def romanToInt(self, s: str) -> int:\n",
    "        romance = {\n",
    "            'I': 1,\n",
    "            'V': 5,\n",
    "            'X': 10,\n",
    "            'L': 50,\n",
    "            'C': 100,\n",
    "            'D': 500,\n",
    "            'M': 1000\n",
    "        }\n",
    "        prev = 0\n",
    "        total = 0\n",
    "        for i in s[-1::-1]:\n",
    "            current = romance[i]\n",
    "            if prev > current:\n",
    "                total -= current\n",
    "            else:\n",
    "                total += current\n",
    "            prev = current\n",
    "        return total"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1910\n"
     ]
    }
   ],
   "source": [
    "print(Solution().romanToInt('MCMX'))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
